﻿using System;
using System.Collections.ObjectModel;
using System.Windows.Controls;

using GalaSoft.MvvmLight.Command;

using NetBay.Core.BusinessEntities;
using NetBay.Core.BusinessEntities.Versioning;

using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Manager.Application.ViewModel.BaseClass;

namespace Rio.Manager.Application.ViewModel.FolderTypeAdministration
{
    public class ListUndoCheckOutTabViewModel : TabViewModelBase
    {
        #region Fields

        private ObservableCollection<VersioningItem> _checkOutUsers;
        private string _dateHeaderLabel;
        private string _documentHeaderLabel;
        private string _folderTypeLabel;
        private string _organizationLabel;
        private FolderType _selectedFolderType;
        private Organization _selectedOrganization;
        private ObservableCollection<VersioningItem> _selectedUsers;
        private string _userHeaderLabel;

        #endregion Fields

        #region Constructors

        public ListUndoCheckOutTabViewModel()
            : base()
        {
            CanCloseTab = true;
            TabIcon = new Uri("/Rio.Manager.Application;component/Assets/Images/list_undo_checkout.png", UriKind.Relative);
        }

        #endregion Constructors

        #region Properties

        public ObservableCollection<VersioningItem> CheckOutUsers
        {
            get { return _checkOutUsers; }
            set
            {
                _checkOutUsers = value;
                RemoveSelectedUsersCommand.RaiseCanExecuteChanged();
                RaisePropertyChanged("CheckOutUsers");
            }
        }

        public string DateHeaderLabel
        {
            get { return _dateHeaderLabel; }
            set
            {
                _dateHeaderLabel = value;
                RaisePropertyChanged("DateHeaderLabel");
            }
        }

        public string DocumentHeaderLabel
        {
            get { return _documentHeaderLabel; }
            set
            {
                _documentHeaderLabel = value;
                RaisePropertyChanged("DocumentHeaderLabel");
            }
        }

        public string FolderTypeLabel
        {
            get { return _folderTypeLabel; }
            set
            {
                _folderTypeLabel = value;
                RaisePropertyChanged("FolderTypeLabel");
            }
        }

        public RelayCommand InitializationCommand
        {
            get;
            set;
        }

        public string OrganizationLabel
        {
            get { return _organizationLabel; }
            set
            {
                _organizationLabel = value;
                RaisePropertyChanged("OrganizationLabel");
            }
        }

        public RelayCommand RemoveSelectedUsersCommand
        {
            get;
            set;
        }

        public override FolderType SelectedFolderType
        {
            get { return _selectedFolderType; }
            set
            {
                if (value != null && value.Identifier > 0)
                {
                    _selectedFolderType = value;
                    RaisePropertyChanged("SelectedFolderType");

                    GetUsersInCheckOut();
                }
            }
        }

        public override Organization SelectedOrganization
        {
            get { return _selectedOrganization; }
            set
            {
                _selectedOrganization = value;
                RaisePropertyChanged("SelectedOrganization");
            }
        }

        public ObservableCollection<VersioningItem> SelectedUsers
        {
            get { return _selectedUsers; }
            set
            {
                _selectedUsers = value;
                RemoveSelectedUsersCommand.RaiseCanExecuteChanged();
                RaisePropertyChanged("SelectedUsers");
            }
        }

        public string UserHeaderLabel
        {
            get { return _userHeaderLabel; }
            set
            {
                _userHeaderLabel = value;
                RaisePropertyChanged("UserHeaderLabel");
            }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Inits the commands.
        /// </summary>
        public override void InitCommands()
        {
            InitializationCommand = new RelayCommand(Initialization);
            RemoveSelectedUsersCommand = new RelayCommand(RemoveSelectedUsers, CanDeleteUsers);
        }

        /// <summary>
        /// Inits the labels.
        /// </summary>
        public override void InitLabels()
        {
            DocumentHeaderLabel = Resx.GetLabel(ResxCommon.DOCUMENT_LABEL).TrimEnd(' ', ':');
            DateHeaderLabel = Resx.GetLabel(ResxCommon.DATE);
            UserHeaderLabel = Resx.GetLabel(ResxCommon.USER);
            OrganizationLabel = Resx.GetLabel(ResxCommon.ORGANIZATION);
            FolderTypeLabel = Resx.GetLabel(ResxCommon.FOLDER_TYPE);

            TabTitle = Resx.GetLabel(ResxRioManager.LIST_UNDO_CHECK_OUT_TAB);
        }

        /// <summary>
        /// Determines whether this instance [can delete users].
        /// </summary>
        /// <returns>
        ///   <c>true</c> if this instance [can delete users]; otherwise, <c>false</c>.
        /// </returns>
        private bool CanDeleteUsers()
        {
            if (CheckOutUsers == null)
                return false;

            if (SelectedUsers == null)
                return false;

            if (CheckOutUsers.Count < 1)
                return false;

            if (SelectedUsers.Count < 1)
                return false;

            return true;
        }

        /// <summary>
        /// Gets the users in check out.
        /// </summary>
        private void GetUsersInCheckOut()
        {
            BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();

            BusyIndicator.Clear();
            BusyIndicator.AddBusyTask();

            businessEntitiesDomainContext.GetCheckOutVersionByFolderType(
                SelectedFolderType.Identifier,
                (retr) =>
                {
                    BusyIndicator.RemoveBusyTask();

                    if (!retr.HasError && retr.Error == null && retr.Value != null)
                    {
                        CheckOutUsers = new ObservableCollection<VersioningItem>(retr.Value);
                    }
                },
                null);
        }

        /// <summary>
        /// Initializations this instance.
        /// </summary>
        private void Initialization()
        {
            InitLabels();
        }

        /// <summary>
        /// Removes the selected users.
        /// </summary>
        private void RemoveSelectedUsers()
        {
            BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();

            BusyIndicator.Clear();

            foreach (var user in SelectedUsers)
            {
                BusyIndicator.AddBusyTask();

                businessEntitiesDomainContext.UndoCheckout(
                    user.VersionId,
                    (retr) =>
                    {
                        BusyIndicator.RemoveBusyTask();

                        if (retr.Error == null && !retr.HasError && retr.Value.Value)
                        {
                            VersioningItem selectedUser = retr.UserState as VersioningItem;

                            SelectedUsers.Remove(selectedUser);
                            CheckOutUsers.Remove(selectedUser);
                        }
                    },
                    user);
            }
        }

        #endregion Methods
    }
}